const express = require("express");
const router = express.Router();
const sqlFn = require("./mysqlConfig");
const jwt = require("jsonwebtoken");
const config = require("./config");

//登陆
router.post("/login", (req, res) => {
    const { username,password } = req.body;
    const sql = "select * from user where `username`=? and `password`=?";
    const arr = [username,password]
    sqlFn(sql, arr, result => {
        if (result.length > 0) {
            const token = jwt.sign({
                id: result[0].id,
                username: result[0].username
            }, config.jwtSecret);
            res.status(200).json(token)
        } else {
            res.status(401).json({
                errors: "用户名密码错误"
            })
        }

    })
})

// 注册
router.post("/register", (req, res) => {
    const { username, password, email } = req.body;
    const sql = "insert into user values(null,?,?,?)";
    const arr = [username, password, email]
    sqlFn(sql, arr, result => {
        if (result.affectedRows > 0) {
            res.status(200).json({
                msg: "注册成功"
            })
        } else {
            res.status(400).json({
                msg: "注册失败"
            })
        }
    })
})

module.exports = router;